package com.css.zfzx.data.primary.hddcActivefaultPositionerrorPG.service.impl;

import com.css.zfzx.data.common.Constant;
import com.css.zfzx.data.common.GenerateSiteCodeUtil;
import com.css.zfzx.data.common.ProvinceCityAreaUtil;
import com.css.zfzx.data.postgresql.fxqhPriorityPG.repository.entity.FxqhPriorityPostgresqlEntity;
import com.css.zfzx.data.postgresql.hddcActivefaultPG.repository.HddcActivefaultRepository;
import com.css.zfzx.data.postgresql.hddcActivefaultPositionerrorPG.repository.HddcActivefaultPositionerrorPostgresqlRepository;
import com.css.zfzx.data.postgresql.hddcActivefaultPositionerrorPG.repository.entity.HddcActivefaultPositionerrorPostgresqlEntity;
import com.css.zfzx.data.postgresql.pgReconciliation.repository.PgReconciliationNativeRepository;
import com.css.zfzx.data.primary.HddcActivefaultPG.repository.entity.HddcActivefaultPGVo;
import com.css.zfzx.data.primary.HddcActivefaultPG.service.HddcActivefaultPGService;
import com.css.zfzx.data.primary.base.repository.SuperRepository;
import com.css.zfzx.data.primary.base.vo.ProxyVO4;
import com.css.zfzx.data.primary.base.vo.ProxyVO7;
import com.css.zfzx.data.primary.base.vo.ProxyVO8;
import com.css.zfzx.data.primary.hddcActivefaultPositionerrorPG.repository.HddcActivefaultPositionerrorPGNativeRepository;
import com.css.zfzx.data.primary.hddcActivefaultPositionerrorPG.repository.entity.HddcActivefaultPositionerrorPGEntity;
import com.css.zfzx.data.primary.hddcActivefaultPositionerrorPG.service.HddcActivefaultPositionerrorPGService;
import com.css.zfzx.data.thirdary.jgReconciliation.repository.entity.SjtgfJghshYjSjdzbEntity;
import com.css.zfzx.data.thirdary.jgReconciliation.service.ReconciliationService;
import com.css.zfzx.data.util.DateUtil;
import com.css.zfzx.data.util.GeometryUtil;
import com.vividsolutions.jts.geom.Geometry;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Log4j2
@Service
public class HddcActivefaultPositionerrorPGServiceImpl implements HddcActivefaultPositionerrorPGService {

    private final HddcActivefaultPositionerrorPGNativeRepository hddcActivefaultPositionerrorPGNativeRepository;
    private final HddcActivefaultPositionerrorPostgresqlRepository repository;
    private final PgReconciliationNativeRepository jgNativeRepository;
    private final ReconciliationService reconciliationService;
    @Autowired
    HddcActivefaultPGService hddcActivefaultPGService;
    @Autowired
    SuperRepository superRepository;
    @Autowired
    public HddcActivefaultPositionerrorPGServiceImpl(HddcActivefaultPositionerrorPGNativeRepository hddcActivefaultPositionerrorPGNativeRepository, HddcActivefaultPositionerrorPostgresqlRepository repository, PgReconciliationNativeRepository jgNativeRepository, ReconciliationService reconciliationService) {
        this.hddcActivefaultPositionerrorPGNativeRepository = hddcActivefaultPositionerrorPGNativeRepository;
        this.repository = repository;
        this.jgNativeRepository = jgNativeRepository;
        this.reconciliationService = reconciliationService;
    }

    /**
     * 新增数据不包含修改
     *
     * @return
     */
    @Override
    public void findDataCreate() {
        LocalDateTime createTime = repository.findCreateTime();
        //查询新增数据
        List<HddcActivefaultPositionerrorPGEntity> yhDisasterEntities = hddcActivefaultPositionerrorPGNativeRepository.findYhDisastersCreate(createTime);
        if (yhDisasterEntities.size() == 0 || yhDisasterEntities == null) {
            System.out.println("hddc_activefault_positionerror:时间" + new Date() + ",添加查询了数据：" + yhDisasterEntities.size() + " 条");
            return;
        }
        List<HddcActivefaultPositionerrorPostgresqlEntity> saveList = new ArrayList<>();
        int flag = 0;
        String startCode = null;
        Map<String,String> errorMap=new HashMap<>();
        List<HddcActivefaultPGVo> voList = hddcActivefaultPGService.findVO();
        for (HddcActivefaultPositionerrorPGEntity entity : yhDisasterEntities) {
            HddcActivefaultPGVo vo=new HddcActivefaultPGVo();
            vo.setId(entity.getId());
            vo.setName(entity.getName());
            vo.setProvince(entity.getProvince());
            vo.setCity(entity.getCity());
            vo.setArea(entity.getArea());
            if (!voList.contains(vo)){
                errorMap.put(entity.getUuid(),"这条数据不合规范");
                continue;
            }
            HddcActivefaultPositionerrorPostgresqlEntity postgresqlEntity = new HddcActivefaultPositionerrorPostgresqlEntity();
            BeanUtils.copyProperties(entity, postgresqlEntity);
            postgresqlEntity.setDistrict(entity.getArea());

            Geometry geometry = GeometryUtil.setRecArea(entity.getExtends15());
            postgresqlEntity.setExtends5(geometry);

            postgresqlEntity.setFxpcDataidSjgl(entity.getUuid());
            String oldSitCode = null;
            if (flag == 0) {
                flag++;
                oldSitCode = repository.getGenerateSiteCode();
            } else {
                oldSitCode = startCode;
            }

            String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
            if (code == null) {
                throw new RuntimeException("province:{}" + entity.getProvince() + "city:{}" + entity.getCity() +
                        "area:{}" + entity.getArea() + "的区划编码获取失败，请检查后再导入");
            }
            String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "");
            startCode = generateSiteCode;
            postgresqlEntity.setFxpcDcdxbmSjgl(generateSiteCode);
            //根据名称获取行政编码
            if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
            }
            if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
            }
            if (!StringUtils.isEmpty(entity.getArea())) {
                postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                postgresqlEntity.setFxpcXzqhbmcSjgl(code);
            }
            //标识数据的当前状态，如果是新增数据，该字段为I；
            // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
            postgresqlEntity.setFxpcSjztSjgl("I");
            //将创建时间转化成字符串形式
            if (entity.getCreateTime() != null) {
                postgresqlEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
            }
            //统一都是默认040
            postgresqlEntity.setFxpcSshySjgl("040");
            //日期分片
            postgresqlEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
            //批次号
            postgresqlEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
            //审核流程状态
            postgresqlEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
            //审核状态
            postgresqlEntity.setFxpcShztSjgl(Constant.SHZT_TG);
            saveList.add(postgresqlEntity);
        }
        long startIn = System.currentTimeMillis();
        int iterable = jgNativeRepository.batchSave1(saveList);
        long endIn = System.currentTimeMillis();
        if (errorMap.size()>0||!errorMap.isEmpty()){
            log.error(errorMap);
        }
        System.out.println("hddc_activefault_positionerror:时间" + new Date() + ",插入数据：" + saveList.size() + " 条,用时  " + (endIn - startIn));
        update(iterable,saveList);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("hddc_activefault_positionerror");
        sjtgfJghshYjSjdzbEntity.setSjts(iterable);
        sjtgfJghshYjSjdzbEntity.setLch(Integer.valueOf("101"));
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }
    private void update(int iterable,List<HddcActivefaultPositionerrorPostgresqlEntity> saveList){
        List<ProxyVO7> proxyVOs=new ArrayList<>();
        for (int i=0;i<iterable;i++) {
            HddcActivefaultPositionerrorPostgresqlEntity pgEntity = saveList.get(i);
            ProxyVO7 proxyVO=new ProxyVO7();
            proxyVO.setUuid(pgEntity.getUuid());
            //proxyVO.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            proxyVO.setIsReportPg("1");
            proxyVOs.add(proxyVO);
        }
        superRepository.batchUpdate(proxyVOs);
    }
    @Override
    public void findDataUpdate() {
        LocalDateTime updateTime = repository.findUpdateTime();
        //查询新增数据
        List<HddcActivefaultPositionerrorPGEntity> yhDisasterEntities = hddcActivefaultPositionerrorPGNativeRepository.findYhDisastersUpdate(updateTime);
        if (yhDisasterEntities.size() == 0 || yhDisasterEntities == null) {
            System.out.println("hddc_activefault_positionerror:时间" + new Date() + ",修改查询了数据：" + yhDisasterEntities.size() + " 条");
            return;
        }
        List<HddcActivefaultPositionerrorPostgresqlEntity> saveList = new ArrayList<>();
        int flag = 0;
        String startCode = null;
        Map<String,String> errorMap=new HashMap<>();
        List<HddcActivefaultPGVo> voList = hddcActivefaultPGService.findVO();
        for (HddcActivefaultPositionerrorPGEntity entity : yhDisasterEntities) {
            HddcActivefaultPGVo vo=new HddcActivefaultPGVo();
            vo.setId(entity.getId());
            vo.setName(entity.getName());
            vo.setProvince(entity.getProvince());
            vo.setCity(entity.getCity());
            vo.setArea(entity.getArea());
            if (!voList.contains(vo)){
                errorMap.put(entity.getUuid(),"这条数据不合规范");
                continue;
            }
            HddcActivefaultPositionerrorPostgresqlEntity postgresqlEntity = new HddcActivefaultPositionerrorPostgresqlEntity();
            BeanUtils.copyProperties(entity, postgresqlEntity);
            postgresqlEntity.setFxpcDataidSjgl(entity.getUuid());
            postgresqlEntity.setDistrict(entity.getArea());
            Geometry geometry = GeometryUtil.setRecArea(entity.getExtends15());
            postgresqlEntity.setExtends5(geometry);

            String oldSitCode = null;
            if (flag == 0) {
                flag++;
                oldSitCode = repository.getGenerateSiteCode();
            } else {
                oldSitCode = startCode;
            }

            String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
            if (code == null) {
                throw new RuntimeException("province:{}" + entity.getProvince() + "city:{}" + entity.getCity() +
                        "area:{}" + entity.getArea() + "的区划编码获取失败，请检查后再导入");
            }
            String generateSiteCode = GenerateSiteCodeUtil.generateSiteCode(code, oldSitCode, "");
            startCode = generateSiteCode;
            postgresqlEntity.setFxpcDcdxbmSjgl(generateSiteCode);
            //根据名称获取行政编码

            if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
            }
            if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
            }
            if (!StringUtils.isEmpty(entity.getArea())) {
                postgresqlEntity.setFxpcXzqhbmaSjgl(code.substring(0, 2) + "0000");
                postgresqlEntity.setFxpcXzqhbmbSjgl(code.substring(0, 4) + "00");
                postgresqlEntity.setFxpcXzqhbmcSjgl(code);
            }
            //标识数据的当前状态，如果是新增数据，该字段为I；
            // 如果数据被更新过，该字段为U；如果数据被删除，该字段为D。
            if (entity.getIsValid().equals("0")) {
                postgresqlEntity.setFxpcSjztSjgl("D");
            } else {
                postgresqlEntity.setFxpcSjztSjgl("U");
            }
            //将创建时间转化成字符串形式
            if (entity.getCreateTime() != null) {
                postgresqlEntity.setFxpcCreatetimeSjgl(DateUtil.getContainsHMS(entity.getCreateTime()));
            }
            if (entity.getUpdateTime() != null) {
                postgresqlEntity.setFxpcUpdatetimeSjgl(DateUtil.getContainsHMS(entity.getUpdateTime()));
            }
            //统一都是默认040
            postgresqlEntity.setFxpcSshySjgl("040");
            //日期分片
            postgresqlEntity.setFxpcRqfpSjgl(DateUtil.getNotContainsHMS(new Date()));
            //批次号
            postgresqlEntity.setFxpcPchSjgl(DateUtil.getNotContainsHMS(new Date()));
            //审核流程状态
            postgresqlEntity.setFxpcShlcztSjgl(Constant.SHLCZT_ZZSH);
            //审核状态
            postgresqlEntity.setFxpcShztSjgl(Constant.SHZT_TG);
            saveList.add(postgresqlEntity);
        }
        long startIn = System.currentTimeMillis();
        int iterable = jgNativeRepository.batchUpdate1(saveList);
        long endIn = System.currentTimeMillis();
        System.out.println("hddc_activefault_positionerror:时间" + new Date() + ",修改数据：" + saveList.size() + " 条,用时  " + (endIn - startIn));
        update(iterable,saveList);
        SjtgfJghshYjSjdzbEntity sjtgfJghshYjSjdzbEntity = new SjtgfJghshYjSjdzbEntity();
        sjtgfJghshYjSjdzbEntity.setBmc("hddc_activefault_positionerror");
        sjtgfJghshYjSjdzbEntity.setSjts(iterable);
        sjtgfJghshYjSjdzbEntity.setLch(Integer.valueOf("201"));
        reconciliationService.saveReconciliation(sjtgfJghshYjSjdzbEntity);
    }
}
